package com.example.test.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.example.test.entity.Song;

import java.util.ArrayList;
import java.util.List;

public class MusicUtils {

    public static List<Song> getMusics(Context context){
        List<Song>  musics = new ArrayList<>();

        //从SD卡中读取
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);

        if (cursor != null){
            while (cursor.moveToNext()){
                //创建Song对象
                Song song = new Song();
                song.setTitle(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
                song.setArtist(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
                song.setDuration(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)));
                song.setData(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));

                //过滤掉短音频
                if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)))>100000){
                    musics.add(song);
                }
            }
            //释放资源
            cursor.close();
        }else {
            Toast.makeText(context, "没有音乐文件", Toast.LENGTH_SHORT).show();
        }
        return musics;
    }

    public static String formatTime(int time){
        if (time / 1000 % 60 < 10){
            return time / 1000 / 60 + ":0" + time / 1000 % 60;
        }else {
            return time /1000 / 60 + ":" + time / 1000 % 60;
        }
    }
}
